<template>
  <el-dialog :title="title" :visible.sync="visible" width="700px" append-to-body @close="close">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="模型名称" prop="name" required>
        <el-input v-model="form.name" placeholder="请输入物模型名称，例如：温度"/>
      </el-form-item>
      <el-form-item label="模型标识" prop="identifier" required>
        <el-input v-model="form.identifier" placeholder="请输入标识符，例如：temperature"/>
      </el-form-item>
      <el-form-item label="模型排序" prop="sort">
        <el-input-number v-model="form.sort" :min="0" :max="999" controls-position="right"/>
      </el-form-item>
      <el-form-item label="模型类别" prop="type" required>
        <el-radio-group v-model="form.type">
          <el-radio label="property">属性</el-radio>
          <el-radio label="function">功能</el-radio>
          <el-radio label="event">事件</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="模型特性">
        <el-checkbox v-model="form.isRealtime" true-label="1" false-label="0">实时监测</el-checkbox>
        <el-checkbox v-model="form.isReadonly" true-label="1" false-label="0">只读数据</el-checkbox>
        <el-checkbox v-model="form.isHistory" true-label="1" false-label="0">历史存储</el-checkbox>
      </el-form-item>
      <el-form-item label="数据类型" prop="dataType" required>
        <el-select v-model="form.dataType" placeholder="请选择数据类型">
          <el-option label="整数型" value="int"/>
          <el-option label="小数型" value="float"/>
          <el-option label="字符串" value="string" :disabled="form.type === 'property'"/>
          <el-option label="布尔型" value="bool" :disabled="form.type === 'property'"/>
          <el-option label="枚举型" value="enum" :disabled="form.type === 'property'"/>
        </el-select>
      </el-form-item>
      <!-- 数值型（整数、小数）特有的表单项 -->
      <template v-if="form.dataType === 'int' || form.dataType === 'float'">
        <el-form-item label="取值范围">
          <el-col :span="11">
            <el-form-item prop="min">
              <el-input v-model="form.min" placeholder="最小值"/>
            </el-form-item>
          </el-col>
          <el-col :span="2" class="text-center">
            <span>-</span>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="max">
              <el-input v-model="form.max" placeholder="最大值"/>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="步长" prop="step">
          <el-input v-model="form.step" placeholder="请输入步长，例如：1"/>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位"/>
        </el-form-item>
      </template>
      <!-- 字符串类型特有的表单项 -->
      <template v-if="form.dataType === 'string'">
        <el-form-item label="最大长度" prop="maxLength">
          <el-input-number v-model="form.maxLength" :min="1" :max="2048" controls-position="right"/>
        </el-form-item>
      </template>
      <!-- 布尔型特有的表单项 -->
      <template v-if="form.dataType === 'bool'">
        <el-form-item label="布尔值">
          <el-col :span="11">
            <el-form-item prop="boolFalseText">
              <el-input v-model="form.boolFalseText" placeholder="例如：关闭"/>
              <div class="sub-text">(0 值对应文本)</div>
            </el-form-item>
          </el-col>
          <el-col :span="2" class="text-center">
            <span></span>
          </el-col>
          <el-col :span="11">
            <el-form-item prop="boolTrueText">
              <el-input v-model="form.boolTrueText" placeholder="例如：打开"/>
              <div class="sub-text">(1 值对应文本)</div>
            </el-form-item>
          </el-col>
        </el-form-item>
      </template>
      <!-- 枚举型特有的表单项 -->
      <template v-if="form.dataType === 'enum'">
        <el-form-item label="展示方式">
          <el-select v-model="form.enumDisplayType" placeholder="请选择展示方式">
            <el-option label="下拉框" value="select"/>
            <el-option label="按钮" value="button"/>
          </el-select>
        </el-form-item>
        <el-form-item label="枚举项">
          <div v-for="(item, index) in form.enumItems" :key="index" class="enum-item">
            <el-col :span="11">
              <el-input v-model="item.value" placeholder="参数值，例如：0"/>
            </el-col>
            <el-col :span="11" :offset="1">
              <el-input v-model="item.text" placeholder="参数描述，例如：中速档位"/>
            </el-col>
            <el-col :span="1">
              <el-button type="text" icon="el-icon-delete" @click="removeEnumItem(index)"/>
            </el-col>
          </div>
          <el-button type="text" icon="el-icon-plus" @click="addEnumItem">添加枚举项</el-button>
        </el-form-item>
      </template>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  name: "ModelForm",
  props: {
    title: {
      type: String,
      default: "添加物模型"
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 表单参数
      form: {
        id: null,
        name: null,
        identifier: null,
        sort: 0,
        type: 'property',
        isRealtime: "0",
        isReadonly: "0",
        isHistory: "0",
        dataType: null,
        min: null,
        max: null,
        step: null,
        unit: null,
        maxLength: 1024,
        boolFalseText: null,
        boolTrueText: null,
        enumDisplayType: "select",
        enumItems: [],
        remark: null
      },
      // 表单校验规则
      rules: {
        name: [
          { required: true, message: "模型名称不能为空", trigger: "blur" }
        ],
        identifier: [
          { required: true, message: "标识符不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "模型类别不能为空", trigger: "change" }
        ],
        dataType: [
          { required: true, message: "数据类型不能为空", trigger: "change" }
        ],
        min: [
          { 
            validator: (rule, value, callback) => {
              if (this.form.dataType === 'int' || this.form.dataType === 'float') {
                if (!value) {
                  callback(new Error('最小值不能为空'));
                } else if (isNaN(value)) {
                  callback(new Error('请输入数字'));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            }, 
            trigger: "blur"
          }
        ],
        max: [
          { 
            validator: (rule, value, callback) => {
              if (this.form.dataType === 'int' || this.form.dataType === 'float') {
                if (!value) {
                  callback(new Error('最大值不能为空'));
                } else if (isNaN(value)) {
                  callback(new Error('请输入数字'));
                } else if (Number(value) <= Number(this.form.min)) {
                  callback(new Error('最大值必须大于最小值'));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            }, 
            trigger: "blur"
          }
        ],
        step: [
          { 
            validator: (rule, value, callback) => {
              if (this.form.dataType === 'int' || this.form.dataType === 'float') {
                if (!value) {
                  callback(new Error('步长不能为空'));
                } else if (isNaN(value)) {
                  callback(new Error('请输入数字'));
                } else if (Number(value) <= 0) {
                  callback(new Error('步长必须大于0'));
                } else {
                  callback();
                }
              } else {
                callback();
              }
            }, 
            trigger: "blur"
          }
        ],
        boolFalseText: [
          { 
            validator: (rule, value, callback) => {
              if (this.form.dataType === 'bool' && !value) {
                callback(new Error('请输入0值对应文本'));
              } else {
                callback();
              }
            }, 
            trigger: "blur"
          }
        ],
        boolTrueText: [
          { 
            validator: (rule, value, callback) => {
              if (this.form.dataType === 'bool' && !value) {
                callback(new Error('请输入1值对应文本'));
              } else {
                callback();
              }
            }, 
            trigger: "blur"
          }
        ]
      }
    };
  },
  watch: {
    'form.type'(newVal) {
      // 当切换到属性类型时，如果当前数据类型不是整数或小数，则重置为null
      if (newVal === 'property' && 
          this.form.dataType !== 'int' && 
          this.form.dataType !== 'float') {
        this.form.dataType = null;
      }
    },
    'form.dataType'(newVal) {
      // 当数据类型改变时，重置相关字段
      if (newVal === 'int' || newVal === 'float') {
        this.form.min = null;
        this.form.max = null;
        this.form.step = '1';
        this.form.unit = null;
        this.form.boolFalseText = null;
        this.form.boolTrueText = null;
        this.form.enumDisplayType = 'select';
        this.form.enumItems = [];
        this.form.maxLength = 1024;
      } else if (newVal === 'bool') {
        this.form.min = null;
        this.form.max = null;
        this.form.step = null;
        this.form.unit = null;
        this.form.boolFalseText = null;
        this.form.boolTrueText = null;
        this.form.enumDisplayType = 'select';
        this.form.enumItems = [];
        this.form.maxLength = 1024;
      } else if (newVal === 'enum') {
        this.form.min = null;
        this.form.max = null;
        this.form.step = null;
        this.form.unit = null;
        this.form.boolFalseText = null;
        this.form.boolTrueText = null;
        this.form.enumDisplayType = 'select';
        this.form.enumItems = [];
        this.form.maxLength = 1024;
      } else if (newVal === 'string') {
        this.form.min = null;
        this.form.max = null;
        this.form.step = null;
        this.form.unit = null;
        this.form.boolFalseText = null;
        this.form.boolTrueText = null;
        this.form.enumDisplayType = 'select';
        this.form.enumItems = [];
        this.form.maxLength = 1024;
      }
    }
  },
  methods: {
    /** 取消按钮 */
    cancel() {
      this.resetForm();
      this.$emit('update:visible', false);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.$emit('submit', this.form);
          this.cancel();
        }
      });
    },
    /** 表单重置 */
    resetForm() {
      this.form = {
        id: null,
        name: null,
        identifier: null,
        sort: 0,
        type: 'property',
        isRealtime: "0",
        isReadonly: "0",
        isHistory: "0",
        dataType: null,
        min: null,
        max: null,
        step: null,
        unit: null,
        maxLength: 1024,
        boolFalseText: null,
        boolTrueText: null,
        enumDisplayType: "select",
        enumItems: [],
        remark: null
      };
      this.$nextTick(() => {
        this.$refs["form"].clearValidate();
      });
    },
    /** 添加枚举项 */
    addEnumItem() {
      this.form.enumItems.push({
        value: '',
        description: ''
      });
    },
    /** 删除枚举项 */
    removeEnumItem(index) {
      this.form.enumItems.splice(index, 1);
    },
    /** 关闭弹窗时的回调 */
    close() {
      this.resetForm();
      this.$emit('update:visible', false);
    }
  }
};
</script>

<style scoped>
.text-center {
  text-align: center;
  line-height: 40px;
}

.sub-text {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.enum-item {
  margin-bottom: 10px;
}
</style> 